package com.mark.web.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mark.common.Constant;
import com.mark.common.ServerResponse;
import com.mark.web.sys.entity.po.Role;
import com.mark.web.sys.entity.vo.RoleVo;
import com.mark.web.sys.mapper.RoleMapper;
import com.mark.web.sys.service.IRoleService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 用户头像POJO类
 * @Author: Mark
 * @CreateDate: 2019/1/13 19:09
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public ServerResponse<String> addRole(Role role) {
        ServerResponse<String> validateRes = validate(role);
        if(!validateRes.isSuccess()){
            return validateRes;
        }
        int insert = roleMapper.insert(role);
        if(insert == Constant.SUCCESS){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("保存角色数据失败！");
    }

    @Override
    public ServerResponse<String> editRole(Role role) {
        ServerResponse<String> validateRes = validate(role);
        if(!validateRes.isSuccess()){
            return validateRes;
        }
        int result = roleMapper.updateByPrimaryKeySelective(role);
        if(result == Constant.SUCCESS){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("保存更新角色数据失败！");
    }

    @Override
    public ServerResponse<PageInfo<RoleVo>> getRoleList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roleList = roleMapper.selectRoleList();
        List<RoleVo> roleVoList = Lists.newArrayList();
        for(Role role : roleList){
            RoleVo roleVo = new RoleVo(role);
            roleVoList.add(roleVo);
        }
        PageInfo<RoleVo> roleVoPageInfo = new PageInfo<>(roleVoList);
        return  ServerResponse.createBySuccess(roleVoPageInfo);
    }

    @Override
    public ServerResponse<RoleVo> getRole(Integer id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if(role == null){
            return ServerResponse.createByErrorMessage("用户信息不存在！");
        }
        RoleVo roleVo = new RoleVo(role);
        return ServerResponse.createBySuccess(roleVo);
    }

    private ServerResponse<String> validate(Role role){
        //校验角色名称是否已经存在
        int effectNum = roleMapper.selectRoleName(role.getId(), role.getName());
        if(effectNum >= Constant.SUCCESS){
            return ServerResponse.createByIllegalArgument("该角色名称已经存在！");
        }
        return ServerResponse.createBySuccess();
    }

}
